package com.fruit.api.controller.fruit;

import com.fruit.bean.entity.fruit.FruitUserAddressInfo;
import com.fruit.bean.vo.front.Rets;
import com.fruit.service.fruit.FruitUserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Description:
 *  用户地址接口
 *
 * @author 轩辚
 * @date 2021/5/6 22:35
 */
@RestController
@RequestMapping("/fruit/address")
public class FruitUserAddressController {

    @Autowired
    private FruitUserAddressService addressService;

    /**
     * 获取用户的联系地址
     * @return
     */
    @PostMapping("/list")
    public Object getAddressList(@RequestBody Map<String,Long> param){
        Long userId = param.get("userId");
        List<FruitUserAddressInfo> userAddressInfoList = addressService.getUserAddressList(userId);
        return Rets.success(userAddressInfoList);
    }

    /**
     * 新增收货地址
     * @return
     */
    @PostMapping("/add")
    public Object addAddress(@RequestBody FruitUserAddressInfo addressInfo){
        if(addressService.getUserAddressList(addressInfo.getUserId()).size() == 0){
            //如果当前没有地址，则将此地址设为默认
            addressInfo.setIsDefault(1);
        }
        addressService.insert(addressInfo);
        return Rets.success();
    }

    /**
     * 删除收货地址
     * @return
     */
    @PostMapping("/delete")
    public Object delAddress(@RequestBody Map<String,Long> param){
        Long addressId = param.get("addressId");
        addressService.delete(addressId);
        return Rets.success();
    }

    /**
     * 选择默认收货地址
     * @return
     */
    @PostMapping("/select")
    public Object selectDefaultAddress(@RequestBody Map<String,Long> param){
        Long addressId = param.get("addressId");
        FruitUserAddressInfo addressInfo = addressService.get(addressId);
        //删除之前的默认地址
        List<FruitUserAddressInfo> addressInfoList = addressService.getUserAddressList(addressInfo.getUserId());
        for(FruitUserAddressInfo addressInfoItem : addressInfoList){
            if(addressInfoItem.getIsDefault() == 1){
                addressInfoItem.setIsDefault(0);
                addressService.update(addressInfoItem);
            }
        }
        addressInfo.setIsDefault(1);
        addressService.update(addressInfo);
        return Rets.success();
    }
}
